package com.phuc.game.tankshooter;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.phuc.game.tankshooter.engine.GamePlay;
import com.phuc.game.tankshooter.engine.InstantEngine;

public class MainActivity extends BaseGameActivity implements IOnSceneTouchListener {
	public static int SCENE_WIDTH = 450;
	public static final int SCENE_HEIGH = 800;
	public static final int SCENE_END_LOCATION = 650;
	
	private static MainActivity mainActivity;
	
	private Engine mEngine;

	private Scene mScene;
	GamePlay game;

	TextView textPoint;
	Button btnBulletNum;
	ImageView imgReloading;
	ImageView imgLife;
	
	public boolean isStop = false;
	public boolean isReloading = false;
	Vibrator vibrator;

	private AdView adView;
	int touchNum;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity = this;
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		touchNum = 0;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (game != null) {
			game.pause();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (game != null) {
			game.resume();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public Engine onLoadEngine() {
		InstantEngine ie = new InstantEngine(SCENE_WIDTH, SCENE_HEIGH, true);
		mEngine = ie.getEngine();
		return mEngine;
	}

	@Override
	public void onLoadResources() {
		GamePlay.initTextures(mEngine, this);
		GamePlay.initMusic(mEngine, this);
	}

	@Override
	public Scene onLoadScene() {
		mEngine.registerUpdateHandler(new FPSLogger());
		game = new GamePlay();
		
		mScene = game.getWelcomeScene();
		mScene.setOnSceneTouchListener(this);
		
		return mScene;
	}

	@Override
	public void onLoadComplete() {
		
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		touchNum++;
		if (touchNum % 150 == 0 && adView != null) {
			adView.setVisibility(View.VISIBLE);
		} else if (touchNum % 156 == 0 && adView != null) {
			adView.setVisibility(View.INVISIBLE);
		}
		
		if (isStop) {
			return false;
		}
		
		if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
			if (isReloading) {
				
			} else {
				float pX = pSceneTouchEvent.getX();
				float pY = pSceneTouchEvent.getY();
				game.createRocket(pX, pY);
			}
		}
		return false;
	}
	
	@Override
	protected void onSetContentView() {
		final FrameLayout frameLayout = new FrameLayout(this);
	    final FrameLayout.LayoutParams frameLayoutLayoutParams =
	    		new FrameLayout.LayoutParams(
	    				FrameLayout.LayoutParams.FILL_PARENT,
	    				FrameLayout.LayoutParams.FILL_PARENT);

	    this.mRenderSurfaceView = new RenderSurfaceView(this);
	    mRenderSurfaceView.setRenderer(mEngine);
	    final FrameLayout.LayoutParams surfaceViewLayoutParams = new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
	    frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);

	    // Add view to scene
	    LayoutInflater inflater = LayoutInflater.from(this);
	    View v = inflater.inflate(R.layout.main, null);
	    textPoint = (TextView)v.findViewById(R.id.main_txtPoint);
	    ((TextView)v.findViewById(R.id.main_txtMax)).setText("Kỷ lục: " + MenuActivity.maxScore);
	    ((TextView)v.findViewById(R.id.main_txtMax)).setTextColor(Color.RED);
	    btnBulletNum = (Button)v.findViewById(R.id.main_btnReload);
	    btnBulletNum.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (isStop) {
					return;
				}
				if (game.getRocketNum() < game.getRocketNumTotal()) {
					game.reloadBulletNum();
					isReloading = true;
					showReloadDialog(true);
				}
			}
		});
	    imgReloading = (ImageView)v.findViewById(R.id.main_imgReloading);
	    imgReloading.setVisibility(View.INVISIBLE);
	    imgLife = (ImageView)v.findViewById(R.id.main_imgLife);
	    
	    // Load Ads
	    adView = (AdView) v.findViewById(R.id.adView);
	    new Thread() {
        	public void run() {
        		adView.loadAd(new AdRequest());
        	}
        }.start();
        adView.setVisibility(View.INVISIBLE);
	    
	    frameLayout.addView(v);

	    //Create any other views you want here, and add them to the frameLayout.

	    this.setContentView(frameLayout, frameLayoutLayoutParams);
	}

	public void runFromUpdateThread(Runnable runnable) {
		runOnUpdateThread(runnable);
	}
	
	public void setPointToText() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				textPoint.setText("SCORE " + game.getPoint());
			}
		});
	}
	
	public void setBulletNumToView() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				btnBulletNum.setText("" + game.getRocketNum());
			}
		});
	}
	
	public void setLifeToView() {
		vibrator.vibrate(200);
		
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				switch (game.getLife()) {
				case 0:
					imgLife.setBackgroundResource(R.drawable.life0);
					break;
				case 1:
					imgLife.setBackgroundResource(R.drawable.life1);
					break;
				case 2:
					imgLife.setBackgroundResource(R.drawable.life2);
					break;
				case 3:
					imgLife.setBackgroundResource(R.drawable.life3);
					break;
				case 4:
					imgLife.setBackgroundResource(R.drawable.life4);
					break;
				default:
					imgLife.setBackgroundResource(R.drawable.life0);
					break;
				}
			}
		});
	}
	
	public static MainActivity getInstant() {
		return mainActivity;
	}
	
	public GamePlay getGamePlay() {
		return this.game;
	}

	public void showReloadDialog(boolean show) {
		if (show) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					imgReloading.setVisibility(View.VISIBLE);
				}
			});
		} else {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					imgReloading.setVisibility(View.INVISIBLE);
				}
			});
		}
	}
	
	public void requestEndGame() {
		isStop = true;
		
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(3000);
					Intent intent = new Intent(MainActivity.this, ResultActivity.class);
					intent.putExtra("Score", game.getPoint());
					game.endGame();
					startActivity(intent);
					finish();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		if (isStop) {
			return;
		}
		Intent intent = new Intent(this, PauseActivity.class);
		startActivityForResult(intent, 1);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 10000) {
			requestEndGame();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mainActivity = null;
		if (adView != null) {
			adView.destroy();
		}
	}
}